﻿using UnityEngine;
using System.Collections;
/////////////////////////////////////////////////////////////////////
// UIWidget 对齐
/////////////////////////////////////////////////////////////////////
public class UIWidgetAligner : MonoBehaviour {
	public UIWidget targetWidget; //要对齐的uiWidget
	public UIWidget.Pivot targetWidgetPivot; //要对齐到那个pivot
	
	public bool isAlign;
	
	private UIWidget curWidget;
	// Use this for initialization
	void Start () {
		curWidget = GetComponent<UIWidget>();
	}
	
	// Update is called once per frame
	void Update () {
		if(isAlign){
			isAlign = false;
			
			Align();
		}
	}
	
	public void Align(){
		if(targetWidget != null && curWidget != null){
			Vector3[] positions = targetWidget.worldCorners;
			Vector3 bl = positions[0];
			Vector3 tl = positions[1];
			Vector3 tr = positions[2];
			Vector3 br = positions[3];
			
			Vector3 pos = new Vector3(tl.x + (tr.x - tl.x) *0.5f,br.y - (br.y-tr.y) * 0.5f,0);
			switch(targetWidgetPivot){
				case UIWidget.Pivot.BottomLeft : pos = bl;break;
				case UIWidget.Pivot.TopLeft : pos = tl;break;
				case UIWidget.Pivot.TopRight : pos = tr;break;
				case UIWidget.Pivot.BottomRight : pos = br;break;
				
				case UIWidget.Pivot.Bottom : pos = new Vector3(pos.x,bl.y,0);break;
				case UIWidget.Pivot.Left : pos = new Vector3(tl.x,pos.y,0);break;
				case UIWidget.Pivot.Top : pos = new Vector3(pos.x,tr.y,0);break;
				case UIWidget.Pivot.Right : pos = new Vector3(tr.x,pos.y,0);break;
			}
			curWidget.transform.position = pos;
		}
	}
}
